package com.example.aussiehealthhelper;

import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExchangeActivity extends AppCompatActivity {

    private TextView tvUpdateTime, tvBuyingRate, tvSellingRate;
    private EditText etRMB, etAUD;
    private TextView tvAUDResult, tvCNYResult;
    private Button btnRefresh;
    private double buyingRate = 0.0;   //现汇买入价
    private double sellingRate = 0.0;  //现汇卖出价

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exchange);

        tvUpdateTime = findViewById(R.id.tvUpdateTime);
        tvBuyingRate = findViewById(R.id.tvBuyingRate);
        tvSellingRate = findViewById(R.id.tvSellingRate);
        etRMB = findViewById(R.id.etRMB);
        etAUD = findViewById(R.id.etAUD);
        tvAUDResult = findViewById(R.id.tvAUDResult);
        tvCNYResult = findViewById(R.id.tvCNYResult);
        btnRefresh = findViewById(R.id.btnRefresh);

        //初始值
        etRMB.setText("100");
        etAUD.setText("100");

        //加载汇率数据
        new FetchExchangeRateTask().execute();

        //刷新按钮点击
        btnRefresh.setOnClickListener(v -> {
            tvBuyingRate.setText("加载中...");
            tvSellingRate.setText("加载中...");
            tvUpdateTime.setText("更新时间: 加载中...");
            new FetchExchangeRateTask().execute();
        });

        //人民币输入框
        etRMB.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                if (buyingRate > 0) {
                    calculateRMBtoAUD();
                }
            }
        });

        //澳元输入框
        etAUD.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                if (sellingRate > 0) {
                    calculateAUDtoCNY();
                }
            }
        });
    }

    //计算人民币转澳元 (使用现汇买入价)
    private void calculateRMBtoAUD() {
        String rmbStr = etRMB.getText().toString().trim();
        if (rmbStr.isEmpty()) {
            tvAUDResult.setText("--");
            return;
        }

        try {
            double rmbAmount = Double.parseDouble(rmbStr);
            double audAmount = (rmbAmount / buyingRate) * 100;
            tvAUDResult.setText(String.format(Locale.getDefault(), "%.2f", audAmount));
        } catch (NumberFormatException e) {
            tvAUDResult.setText("--");
        }
    }

    //计算澳元转人民币 (使用现汇卖出价)
    private void calculateAUDtoCNY() {
        String audStr = etAUD.getText().toString().trim();
        if (audStr.isEmpty()) {
            tvCNYResult.setText("--");
            return;
        }

        try {
            double audAmount = Double.parseDouble(audStr);
            double rmbAmount = (audAmount * sellingRate) / 100;
            tvCNYResult.setText(String.format(Locale.getDefault(), "%.2f", rmbAmount));
        } catch (NumberFormatException e) {
            tvCNYResult.setText("--");
        }
    }

    private class FetchExchangeRateTask extends AsyncTask<Void, Void, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            btnRefresh.setEnabled(false);
        }

        @Override
        protected String doInBackground(Void... voids) {
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;
            try {
                URL url = new URL("https://www.boc.cn/sourcedb/whpj/");
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.setConnectTimeout(5000);
                urlConnection.connect();

                InputStream inputStream = urlConnection.getInputStream();
                if (inputStream == null) {
                    return null;
                }

                reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder buffer = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line).append("\n");
                }

                if (buffer.length() == 0) {
                    return null;
                }
                return buffer.toString();
            } catch (IOException e) {
                return null;
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        @Override
        protected void onPostExecute(String html) {
            super.onPostExecute(html);
            btnRefresh.setEnabled(true);

            if (html == null) {
                tvBuyingRate.setText("加载失败");
                tvSellingRate.setText("加载失败");
                tvUpdateTime.setText("更新时间: 网络错误");
                Toast.makeText(ExchangeActivity.this, "汇率获取失败，请检查网络", Toast.LENGTH_SHORT).show();
                return;
            }

            //解析澳大利亚元汇率
            parseExchangeRate(html);
        }
    }

    private void parseExchangeRate(String html) {
        try {
            //查找澳大利亚元的现汇买入价和现汇卖出价
            Pattern pattern = Pattern.compile("<td>澳大利亚元</td>\\s*<td>(\\d+\\.\\d+)</td>\\s*<td>(\\d+\\.\\d+)</td>\\s*<td>(\\d+\\.\\d+)</td>");
            Matcher matcher = pattern.matcher(html);

            if (matcher.find()) {
                // 现汇买入价是匹配的第一个值
                String buying = matcher.group(1);
                // 现汇卖出价是匹配的第三个值
                String selling = matcher.group(3);

                buyingRate = Double.parseDouble(buying);
                sellingRate = Double.parseDouble(selling);

                tvBuyingRate.setText(buying);
                tvSellingRate.setText(selling);

                // 获取更新时间
                pattern = Pattern.compile("<td class=\"pjrq\">(\\d{4}\\.\\d{2}\\.\\d{2} \\d{2}:\\d{2}:\\d{2})</td>");
                matcher = pattern.matcher(html);

                if (matcher.find()) {
                    String updateTime = matcher.group(1);
                    tvUpdateTime.setText("更新时间: " + updateTime);
                } else {
                    String currentTime = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss", Locale.getDefault()).format(new Date());
                    tvUpdateTime.setText("更新时间: " + currentTime);
                }

                //根据初始值计算汇率
                calculateRMBtoAUD();
                calculateAUDtoCNY();
            } else {
                throw new Exception("未找到汇率数据");
            }
        } catch (Exception e) {
            buyingRate = 0.0;
            sellingRate = 0.0;
            tvBuyingRate.setText("数据异常");
            tvSellingRate.setText("数据异常");
            tvUpdateTime.setText("更新时间: 解析错误");
            Toast.makeText(this, "汇率解析失败，请稍后再试", Toast.LENGTH_SHORT).show();
        }
    }
}